package cn.drenal.capcap.exception;

import cn.dev33.satoken.exception.NotLoginException;
import cn.dev33.satoken.exception.NotPermissionException;
import cn.dev33.satoken.exception.NotRoleException;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import cn.drenal.capcap.common.Response;
import cn.drenal.capcap.common.ResponseCode;

/**
 * 全局异常处理器
 * 用于统一处理Sa-Token的权限认证异常
 */
@RestControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 处理未登录异常
     */
    @ExceptionHandler(NotLoginException.class)
    @ResponseStatus(HttpStatus.UNAUTHORIZED)
    public Response<String> handleNotLoginException(NotLoginException e) {
        return Response.error(ResponseCode.UNAUTHORIZED, e.getType());
    }

    /**
     * 处理角色权限不足异常
     */
    @ExceptionHandler(NotRoleException.class)
    @ResponseStatus(HttpStatus.FORBIDDEN)
    public Response<Void> handleNotRoleException(NotRoleException e) {
        return Response.custom(ResponseCode.FORBIDDEN.getCode(), "无此角色权限：" + e.getRole(), null);
    }

    /**
     * 处理权限不足异常
     */
    @ExceptionHandler(NotPermissionException.class)
    @ResponseStatus(HttpStatus.FORBIDDEN)
    public Response<Void> handleNotPermissionException(NotPermissionException e) {
        return Response.custom(ResponseCode.FORBIDDEN.getCode(), "无此操作权限：" + e.getPermission(), null);
    }

    /**
     * 处理业务异常
     *
     * @param e 业务异常
     * @return 统一响应体
     */
    @ExceptionHandler(BizException.class)
    public Response<Void> handleBizException(BizException e) {
        return Response.custom(e.getCode(), e.getMessage(), null);
    }

    /**
     * 处理其他未知异常
     *
     * @param e 未知异常
     * @return 统一响应体
     */
    @ExceptionHandler(Exception.class)
    public Response<Void> handleException(Exception e) {
        return Response.error(ResponseCode.INTERNAL_SERVER_ERROR);
    }
}